package pac;

import java.awt.BorderLayout;
import java.io.FileReader;
import java.io.IOException;
import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import java.awt.FlowLayout;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

import javax.swing.JButton;

import BackEnd.IFolio;
import BackEnd.Stock;

public class frame extends JFrame implements WindowListener, ActionListener {

	/**
	 * 
	 */
	private JPanel contentPane;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private frame frame;
	private JTable table_1;
	private Object[][] data;
	DefaultTableModel model;
	public frame(final IFolio folio) {


		final updateThread updater = new updateThread(folio);
		updater.start();

		final int SHORTCUT_MASK = Toolkit.getDefaultToolkit()
				.getMenuShortcutKeyMask();
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setTitle("Folio Tracker");
		setBounds(100, 100, 592, 581);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnMenu = new JMenu("Menu");
		menuBar.add(mnMenu);

		JMenu mnStocks = new JMenu("Update Stocks");
		menuBar.add(mnStocks);

		JMenuItem mntmUpdate = new JMenuItem("Update Now");
		mntmUpdate.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// Code for updating the stocks
				// table.clear
				for (String s : folio.getFoliomap().keySet()) {
					// for each stored ticker,
					// table.add(folio.getX(s), folio.getY(s), folio.getZ(s))
					System.out.println(s + " numShares:"+ folio.getNumShares(s));
				}

			}
		});
		mnStocks.add(mntmUpdate);

		JMenu mnSettings = new JMenu("Settings");
		menuBar.add(mnSettings);

		final JCheckBoxMenuItem buttonOnTop = new JCheckBoxMenuItem(
				"Always on Top");

		buttonOnTop.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (buttonOnTop.getSelectedObjects() == null)
					setOnTop(false);
				else
					setOnTop(true);
			}
		});
		mnSettings.add(buttonOnTop);

		JMenuItem mntmEditSettings = new JMenuItem("Edit Settings");
		mntmEditSettings.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
				SHORTCUT_MASK));
		mntmEditSettings.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				settings set = new settings();
				set.setVisible(true);
			}
		});
		mnSettings.add(mntmEditSettings);

		JMenuItem mntmNewMenuItem = new JMenuItem("New Stock");
		mntmNewMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
				SHORTCUT_MASK));
		mntmNewMenuItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				newStock newS = new newStock(folio, model);
				newS.setVisible(true);
			}
		});
		mnMenu.add(mntmNewMenuItem);

		JMenuItem mntmSave = new JMenuItem("Save");
		mntmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
				SHORTCUT_MASK));
		mntmSave.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				folio.save();
			}
		});
		mnMenu.add(mntmSave);

		JMenuItem mntmLoad = new JMenuItem("Load");
//		System.out.println("test");
		mntmLoad.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
				SHORTCUT_MASK));
		mntmLoad.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
//				System.out.println("test");
				String sName;
				sName = JOptionPane.showInputDialog(null,
						"Enter file name");
				sName = sName + ".txt";
				try{
					BufferedReader in = new BufferedReader(new FileReader(sName));
					String s1;
					while((s1 = in.readLine()) != null){

						// Chop up string to get seperate information
						StringTokenizer split = new StringTokenizer(s1);
						String stockName = split.nextToken(" ");
						String stockNum = split.nextToken(" ");
						String overallCost = split.nextToken(" ");
						int snum = Integer.parseInt(stockNum);
						//				int totalstocks = snum + numSto;
						newStock newS = new newStock(folio, model);
						newS.addFolio(folio, model, stockName, snum);
					}

				}catch (IOException e1){
					JOptionPane.showMessageDialog(null, "File not Found");
				}
			}
		});
		mnMenu.add(mntmLoad);

		JMenuItem mntmQuit = new JMenuItem("Logout");
		mntmQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,
				SHORTCUT_MASK));
		mntmQuit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				(new login()).setVisible(true);
				updater.interrupt();
				dispose();
			}
		});
		mnMenu.add(mntmQuit);

		JTabbedPane tabbedPane = new JTabbedPane();

		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(5, 11, 563, 437);
		contentPane.add(panel);

		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane);
		model = new DefaultTableModel();
		table_1 = new JTable(model);
		model.addColumn("Ticker Symbol");
		model.addColumn("# of Shares");
		model.addColumn("Price Paid");
		model.addColumn("Current Price");
		model.addColumn("Total Value");
		model.addColumn("Profit/Loss");


		table_1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		scrollPane.setViewportView(table_1);
		table_1.setAutoCreateRowSorter(true);

		// table_1.setBorder(new LineBorder(new Color(0, 0, 0)));

		JPanel panel_1 = new JPanel();
		panel_1.setBounds(0, 493, 568, 30);
		contentPane.add(panel_1);
		panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel lblTotals = new JLabel("Totals");
		lblTotals.setFont(new Font("Tahoma", Font.BOLD, 14));
		panel_1.add(lblTotals);

		JLabel lblTickerSymbol = new JLabel("# of Shares:");
		panel_1.add(lblTickerSymbol);

		textField = new JTextField();
		panel_1.add(textField);
		textField.setColumns(5);

		JLabel lblNumberOfShares = new JLabel("Bought At:");
		panel_1.add(lblNumberOfShares);

		textField_1 = new JTextField();
		panel_1.add(textField_1);
		textField_1.setColumns(5);

		JLabel lblCostValue = new JLabel("Value:");
		panel_1.add(lblCostValue);

		textField_2 = new JTextField();
		panel_1.add(textField_2);
		textField_2.setColumns(5);

		JLabel lblProfit = new JLabel("Profit:");
		panel_1.add(lblProfit);

		textField_3 = new JTextField();
		panel_1.add(textField_3);
		textField_3.setColumns(5);

		JButton btnAddStock = new JButton("Add");
		btnAddStock.setBounds(94, 459, 97, 23);
		btnAddStock.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// Add stock
				newStock newS = new newStock(folio, model);
				newS.setVisible(true);

			}
		});
		contentPane.add(btnAddStock);

		JButton btnDeleteStock = new JButton("Delete");
		btnDeleteStock.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				folio.removeStock((String) table_1.getModel().getValueAt(
						table_1.getSelectedRow(), 0));

				delete();

			}
		});
		btnDeleteStock.setBounds(379, 459, 97, 23);
		contentPane.add(btnDeleteStock);
		updateTotals();
	}

	private void save() {
		// Save the current folio!
	}

	private void delete() {
		// Gets the number of the row selected of the table (starting at 0!)
		// Code to delete it
		model.removeRow(table_1.getSelectedRow());

	}

	public void setOnTop(boolean onTop) {
		this.setAlwaysOnTop(onTop);

	}

	private void exit() {
		// Display confirm dialog
		int confirmed = JOptionPane.showConfirmDialog(frame,
				"Are you sure you want to quit?", "Confirm Quit",
				JOptionPane.YES_NO_OPTION);

		// Close if user confirmed
		if (confirmed == JOptionPane.YES_OPTION) {
			// Close frame
			System.exit(0);
		}
	}

	private void updateTotals() {
		// Get total number of stocks
		int stockno = 0;
		for (int i = 0; i < table_1.getRowCount(); i++) {
			stockno = stockno + (Integer) table_1.getValueAt(i, 1);
		}
		// Set total box
		String text = Integer.toString(stockno);
		textField.setText(text);

		// Get total paid of stocks
		double cost = 0;
		for (int i = 0; i < table_1.getRowCount(); i++) {
			cost = cost + (Double) table_1.getValueAt(i, 2);
		}
		// Set total box
		String costText = Double.toString(roundTwoDecimals(cost));
		textField_1.setText(costText);

		// Get total value of stocks
		double value = 0;
		for (int i = 0; i < table_1.getRowCount(); i++) {
			value = value + (Double) table_1.getValueAt(i, 4);
		}
		// Set total box
		String valueText = Double.toString(roundTwoDecimals(value));
		textField_2.setText(valueText);

		// Get total profit
		double profit = 0;
		for (int i = 0; i < table_1.getRowCount(); i++) {
			profit = profit + (Double) table_1.getValueAt(i, 5);
		}
		// Set total box
		String profitText = Double.toString(roundTwoDecimals(profit));
		textField_3.setText(profitText);

	}

	double roundTwoDecimals(double d) {
		DecimalFormat twoDForm = new DecimalFormat("#.##");
		return Double.valueOf(twoDForm.format(d));
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowClosing(WindowEvent arg0) {
		exit();

	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub

	}

}
